<template>
	<div class="container-wrap">
		<description logo="iconfont icon-mulu" :title="title" :desc="desc" />
		<el-card class="table-wrap" shadow="never">
			<div class="operation mb15">
				<div>
					<el-input clearable v-model="searchInput" placeholder="请输入名称" class="width-150 mr10"></el-input>
					<el-button type="primary" @click="search">搜索</el-button>
				</div>
				<div>
					<el-button type="primary" @click="useGuide" :disabled="!state.dirTable.currentRow">使用向导</el-button>
					<el-button type="primary" @click="createDir">创建</el-button>
					<el-button type="danger" @click="delDir" :disabled="!state.dirTable.currentRow">删除</el-button>
					<el-button type="primary" @click="getDirList(true)">刷新</el-button>
				</div>
			</div>
			<el-table
				ref="tableRef"
				border
				v-loading="state.dirTable.loading"
				element-loading-text="数据加载中..."
				:data="state.dirTable.data"
				highlight-current-row
				row-key="storagedirName"
				height="calc(100vh - 455px)"
				@current-change="handleCurrentChange"
			>
				<el-table-column prop="storageDirName" label="名称" min-width="130" show-overflow-tooltip />
				<el-table-column prop="fsName" label="文件系统" min-width="130" show-overflow-tooltip />
				<el-table-column prop="storageDirAuthId" label="授权用户" min-width="130" show-overflow-tooltip />
				<el-table-column prop="storageDirAuthKey" label="授权key" min-width="130" show-overflow-tooltip />
				<el-table-column prop="storageDirUsedSize" label="存储用量" min-width="100" show-overflow-tooltip>
					<template #default="{row}">
						{{formatUnits(row.storageDirUsedSize)}}
					</template>
				</el-table-column>
				<el-table-column prop="storageDirTotalSize" label="存储容量" min-width="100" show-overflow-tooltip>
					<template #default="{row}">
						{{formatUnits(row.storageDirTotalSize)}}
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:current-page="state.dirTable.params.pageNum"
				v-model:page-size="state.dirTable.params.pageSize"
				@current-change="onHandleCurrentChange"
				@size-change="onHandleSizeChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30, 50]"
				background
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.dirTable.total"
			>
			</el-pagination>
		</el-card>

		<el-dialog title="创建存储目录" v-model="createDirVisible" :destroy-on-close="true" width="600px">
			<CreateDir ref="createDirRef" v-model:value="createDirVisible"></CreateDir>
			<template #footer>
				<el-button @click="createDirVisible = false">取消</el-button>
				<el-button type="primary" @click="handlecreateDir">确定</el-button>
			</template>
		</el-dialog>

		<el-dialog title="存储目录使用向导" v-model="guideVisible" :destroy-on-close="true" width="800px">
			<DirGuide ref="dirGuideRef" :selectRow="state.dirTable.currentRow"></DirGuide>
			<template #footer>
				<el-button @click="guideVisible = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, getCurrentInstance, onUnmounted, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useFileStorageApi } from '/@/api/file-storage';
import { formatUnits } from '/@/utils/other';

export interface DirTableRow{
	storageDirName:string,
	storageDirPath:string,
	storageDirUsedSize:string,
	storageDirTotalSize:string,
	storageDirAuthId:string,
	storageDirAuthKey:string,
	fsName:string,
	storageDirMonAddrs?:string
}
interface DirTableState{
	dirTable:{
		data:DirTableRow[],
		loading:boolean,
		params:{
			storageDirName:string,
			pageNum:number,
			pageSize:number
		},
		total:number,
		currentRow: DirTableRow | null | undefined,
	}
}

const Description = defineAsyncComponent(() => import('/@/components/description/index.vue'));
const CreateDir = defineAsyncComponent(() => import('./components/createDir.vue'));
const DirGuide = defineAsyncComponent(() => import('./components/dirGuide.vue'));

const title = '存储目录';
const desc = '存储目录是文件系统的子系统，不同的客户端挂载不同的子目录实现数据隔离访问';
const tableRef = ref();
const fileStorageApi = useFileStorageApi();
const state = reactive<DirTableState>({
	dirTable: {
		data: [],
		loading: false,
		params: {
			storageDirName: '',
			pageNum: 1,
			pageSize: 10
		},
		total: 0,
		currentRow: null,
	}
});

const getDirList = (refresh:boolean = false) => {
	// Display loading
	refresh && (state.dirTable.loading = true);
	fileStorageApi.getStorageDirList({
		pageNo: state.dirTable.params.pageNum,
		pageSize: state.dirTable.params.pageSize,
		storageDirName: state.dirTable.params.storageDirName === '' ? undefined : state.dirTable.params.storageDirName
	}).then((res:any) => {
		state.dirTable.data = res.data.records;
		state.dirTable.total = res.data.total;
	}).catch(() => {
		state.dirTable.data = [];
	}).finally(() => {
		state.dirTable.loading = false;
	});
};
getDirList(true);

const searchInput = ref('');
const search = () => {
	state.dirTable.params.storageDirName = searchInput.value;
	getDirList(true);
};

const handleCurrentChange = (val:DirTableRow | null | undefined) => {
	state.dirTable.currentRow = val;
};
const onHandleCurrentChange = () => {
	getDirList(true);
};
const onHandleSizeChange = () => {
	state.dirTable.params.pageNum = 1;
	getDirList(true);
};

// ws refresh list
const { proxy } = <any>getCurrentInstance();
proxy.mittBus.on('refresh-list', () => {
	getDirList(true);
});
onUnmounted(() => {
	proxy.mittBus.off('refresh-list');
});

// create a new directory
const createDirVisible = ref(false);
const createDir = () => {
	createDirVisible.value = true;
};
const createDirRef = ref();
const handlecreateDir = () => {
	createDirRef.value.createDir();
};

// use guide
const guideVisible = ref(false);
const useGuide = () => {
	guideVisible.value = true;
};

// delete directory
const delDir = () => {
	let { currentRow } = toRefs(state.dirTable);
	if (!currentRow.value) {
		ElMessage.warning(`请先选择要删除的文件系统`);
	} else {
		ElMessageBox.confirm(
			`删除存储目录 ${currentRow.value?.storageDirName} 将会删除全部数据，是否确认删除？`,
			'删除存储目录',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			state.dirTable.loading = true;
			fileStorageApi.delStorageDir({
				storageDirName: currentRow.value?.storageDirName,
				fsName: currentRow.value?.fsName
			}).then(() => {
				ElMessage.success(`添加【删除存储目录${currentRow.value?.storageDirName}】任务成功`);
				tableRef.value?.setCurrentRow();
			}).finally(() => {
				state.dirTable.loading = false;
			});
		});
	}
};
</script>